const adminModle = require('../moogodb/index')

// 查询所有管理员信息
exports.getAllInfo = async (req, res) => {
  try {
    const a = await adminModle.find()
    // console.log(a);
    res.send({
      status: 200,
      message: '查询成功',
      data: a
    })
  } catch (error) {
    console.log(error);
  }
}
// 注册管理员信息
exports.admin = async (req, res) => {
  try {
    // let pwd = '123456'
    console.log(req.body.password);
    const crypto = require('crypto')
    const md5 = crypto.createHash('md5')
    pwd = md5.update(req.body.password).digest('hex')
    //使用adminModel添加数据
    const r = await adminModle.create({
      username: req.body.username,
      password: pwd
    })
    res.send({
      status: 200,
      message: '用户创建成功'
    })
    console.log(r);
    return
  } catch (error) {
    return console.log(error);
  }
}
// 通过姓名更新管理员密码
exports.updateAdmin = async (req, res) => {
  try {
    let info = req.body
    const crypto = require('crypto')
    const md5 = crypto.createHash('md5')
    pwd = md5.update(info.password).digest('hex')
    await adminModle.updateOne({
      username: req.params.username,
      password: pwd
    }
    )
    res.send({
      status: 200,
      message: '修改数据成功'
    })
    return
  } catch (error) {
    console.log(error + '错误信息');
    res.send(error)
  }
}
// 管理员登录
exports.login = async (req, res) => {
  let { username, password } = req.body
  const crypto = require('crypto')
  const md5 = crypto.createHash('md5')
  password = md5.update(password).digest('hex')
  const result = await adminModle.findOne({ username, password })
  console.log(result);
  if (result) {
    res.send({
      status: 'success',
      message: result,
    })
  } else {
    res.send({
      status: 'error',
    })
  }
}
